import * as fs from "fs";
import * as child_process from "child_process";

import log from "../lib/log";
import { compile } from "../lib/compile";
import { Service } from "../lib/service";

export default class consulTemplate extends Service {
    public async start(): Promise<Service> {
        const { bin, pid, hcl, template, nginxCtmpl } = this.config.service["consul-template"];
    
        // consul模板配置模板
        let templateConfigTemplate = fs.readFileSync(template).toString();
    
        // 组装编译数据
        const data = {
            nginxCtmpl,
            nginxBin: this.config.service.nginx.bin,
            nginxDir: this.config.service.nginx.root,
            nginxConfig: this.config.service.nginx.nginxConfig,
        };
    
        // 编译模板写入模板配置
        fs.writeFileSync(hcl, compile(templateConfigTemplate, data));
    
        const argList = ["-config", hcl, `-pid-file=${ pid }`];
        log.app.info(`启动consul-template:  ${ bin } ${ argList.join(" ") }`);

        return super.start(bin, argList);
    }

    public run(cmd: string, argList: string[]): child_process.ChildProcessWithoutNullStreams {
        const worker = child_process.spawn(cmd, argList);
        worker.stdout.on("data", (data: string) => {
            if (this.filter(data)) {
                log[this.serviceName].info(data.toString());
            }
        });
        worker.stderr.on("data", (data: string) => {
            log[this.serviceName].error(data.toString());
        });
        return worker;
    }

    public configService() {}

    public async healthChecks(type: string): Promise<boolean> {
        return type === "start";
    }
}